/**
 * @description 加密库列表
 * 组内传入初始化数据，打开不用调用请求。
 */
import React from 'react';
import PropTypes from 'prop-types';
import { Dialog, Table } from '@teamix/ui';
import Pagination from 'components/commonPagination';
import { Title } from '@alife/devops-ui';
import { getEncryptedProjectsInGroup, getAllEncryptedProjects } from 'api/index.js';
import './index.scss';
import intl from '../../locale';

const { id: org_id } = window.FORCE.organization;

export default class ReposDialog extends React.Component {
  static propTypes = {
    trigger: PropTypes.element,
    isGroup: PropTypes.bool,
    groupId: PropTypes.number,
    initialList: PropTypes.array,
    total: PropTypes.number,
    keyId: PropTypes.string,
  };

  static defaultProps = {
    trigger: null,
    keyId: '',
    isGroup: false, // 组内
    groupId: '',
    total: 0,
    initialList: [],
  };

  constructor(props) {
    super(props);

    this.state = {
      isModalOpen: false,
      isLoading: true,
      page: 1,
    };
  }

  static getDerivedStateFromProps(props) {
    if (props.trigger) {
      return {};
    }
    return {
      isModalOpen: props.isModalOpen,
    };
  }

  componentDidMount() {
    const { initialList, total, isGroup } = this.props;
    if (isGroup) {
      this.setState({
        list: initialList,
        total,
        isLoading: false,
      });
    }
  }

  getData(page) {
    this.setState({
      isLoading: true,
    });

    const { keyId, isGroup, groupId } = this.props;
    let listPromise;
    if (isGroup) {
      listPromise = getEncryptedProjectsInGroup(
        {
          groupId,
        },

        {
          per_page: 10,
          page,
        },
      );
    } else {
      listPromise = getAllEncryptedProjects(
        {
          org_id,
          id: keyId,
        },

        {
          per_page: 10,
          page,
        },
      );
    }

    listPromise
      .then((result) => {
        const [amountInfo, ...list] = result;
        const total = amountInfo.amount || 0;
        this.setState({
          list,
          isLoading: false,
          total,
          page,
        });
      })
      .catch(() => {
        this.setState({
          isLoading: false,
        });
      });
  }

  showModal = () => {
    // 企业设置打开弹窗时触发请求，组内由于外部已经请求过，不请求
    if (!this.props.isGroup) {
      this.getData(1);
    }

    this.setState({
      isModalOpen: true,
    });
  };

  onClose = () => {
    this.setState({
      isModalOpen: false,
    });

    this.props.closeModal && this.props.closeModal();
  };

  onPageNoChange = (page) => {
    this.getData(page);
  };

  render() {
    const { list, isLoading, total, page } = this.state;
    const { isGroup } = this.props;
    return (
      <React.Fragment>
        {this.state.isModalOpen ? (
          <Dialog
            title={
              isGroup
                ? intl.get({
                    id: 'code-assets.components.encryptedProjectsDialog.EncryptedSublibrary',
                    defaultMessage: '已加密子库',
                  })
                : intl.get({
                    id: 'code-assets.components.encryptedProjectsDialog.EffectiveRepository',
                    defaultMessage: '已生效仓库',
                  })
            }
            visible
            onCancel={this.onClose}
            onClose={this.onClose}
            footer={false}
            className="crypto-success-dialog"
            width={600}
          >
            <Table
              className={'fail-repos-table no-border-table'}
              hasBorder={false}
              dataSource={list}
              loading={isLoading}
            >
              <Table.Column
                title={intl.get({
                  id: 'code-assets.components.encryptedProjectsDialog.CodeBase',
                  defaultMessage: '代码库',
                })}
                dataIndex="name"
                cell={(value, index, record) => {
                  return (
                    <Title
                      align="t"
                      trigger={
                        <a
                          href={`/${record.path_with_namespace}/settings`}
                          target="_blank"
                          rel="noreferrer"
                        >
                          {record.name}
                        </a>
                      }
                    >
                      <div>{record.name}</div>
                    </Title>
                  );
                }}
                className={'repo-col'}
                width={200}
              />

              <Table.Column
                title={intl.get({
                  id: 'code-assets.components.encryptedProjectsDialog.DatabaseAdministrator',
                  defaultMessage: '库管理员',
                })}
                dataIndex="error_msg"
                cell={(value, index, record) => {
                  const admins =
                    record.admin_users && record.admin_users.length
                      ? record.admin_users.map((item) => item.name).join('，')
                      : '-';
                  return (
                    <Title align="t" trigger={<span>{admins}</span>}>
                      {admins}
                    </Title>
                  );
                }}
                className="reason-col"
                width={300}
              />
            </Table>
            <Pagination
              onChange={this.onPageNoChange}
              current={page}
              total={total}
              showJump={false}
              hideOnlyOnePage
            />
          </Dialog>
        ) : null}
        {!!this.props.trigger &&
          React.cloneElement(this.props.trigger, { onClick: this.showModal })}
      </React.Fragment>
    );
  }
}
